package threadjuc;

import java.util.Vector;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/28 15:22
 * 异步任务
 */
public class Juc14 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //执行一个异步任务 发起时不会占用主线程的时间  无返回值
        CompletableFuture<Void> async = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                System.out.println("嘿嘿");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("哈哈");
        System.out.println(async.get());

        System.out.println("+++++++++++++++++++++++++++++++++++++");

        //供给型接口
        CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
            int i = 1/0;
            return "成功";
        // 当完成任务后
        }).whenComplete((t, u) -> {
            System.out.println("正确："+ t);   //正常的返回结果
            System.out.println("错误："+ u);   //错误的返回结果
        //当返回异常
        }).exceptionally((e) -> {
            e.printStackTrace();
            return "失败";
        });
        System.out.println(stringCompletableFuture.get());

    }
}
